<template>
  <div id="pageTagList">
    <v-container grid-list-xl fluid>
      <v-layout row warp>
        <v-flex xs12>
          <v-container>
            <v-text-field
              v-model="search"
              id="search"
              key="search"
              label="搜索"
              append-icon="search"
              clearable
              hide-details
              single-line
              solo
              light
              @keyup.enter="init"
            />
          </v-container>
          <v-card class="mb-4">
            <v-toolbar color="primary lighten-1" dark flat dense cad>
              <v-toolbar-title class="subheading">标签管理</v-toolbar-title>
              <v-spacer></v-spacer>
              <v-dialog v-model="dialog" persistent max-width="600px">
                <v-btn slot="activator" flat dark>
                  <v-icon>add</v-icon>&nbsp;新建
                </v-btn>
                <v-card>
                  <v-card-title>
                    <span class="headline">{{ formTitle }}</span>
                  </v-card-title>
                  <v-card-text>
                    <v-container grid-list-md>
                      <v-form>
                        <v-layout wrap>
                          <v-flex xs12>
                            <v-text-field
                              name="name"
                              label="标签名*"
                              v-validate="'required'"
                              data-vv-as="标签名"
                              data-vv-validate-on="blur"
                              :error="errors.has('name')"
                              :error-messages="errors.collect('name')"
                              v-model="editedItem.name"
                            ></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field
                              name="slug"
                              label="标识*"
                              v-validate="'required'"
                              data-vv-as="标识"
                              data-vv-validate-on="blur"
                              :error="errors.has('slug')"
                              :error-messages="errors.collect('slug')"
                              v-model="editedItem.slug"
                            ></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-text-field name="icon" label="图标" v-model="editedItem.icon"></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-combobox
                              v-model="editedItem.color"
                              name="color"
                              :items="color"
                              label="颜色"
                              chips
                              clearable
                            >
                              <template slot="selection" slot-scope="data">
                                <v-chip :selected="data.selected" :color="data.item" dark>
                                  <v-icon>color_lens</v-icon>
                                  <strong>{{ editedItem.name }}</strong>&nbsp;
                                </v-chip>
                              </template>
                            </v-combobox>
                          </v-flex>
                        </v-layout>
                      </v-form>
                    </v-container>
                  </v-card-text>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" flat @click="close">取消</v-btn>
                    <v-btn color="blue darken-1" flat @click="save">保存</v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </v-toolbar>
            <v-divider></v-divider>
            <v-card-text>
              <v-data-table
                v-model="selected"
                :headers="headers"
                :items="tags"
                :pagination.sync="pagination"
                :total-items="totalTags"
                :loading="loading"
                select-all
                item-key="id"
              >
                <template slot="headers" slot-scope="props">
                  <tr>
                    <th>
                      <v-checkbox
                        :input-value="props.all"
                        :indeterminate="props.indeterminate"
                        primary
                        hide-details
                        @click.stop="toggleAll"
                      ></v-checkbox>
                    </th>
                    <template v-for="header in props.headers">
                      <th v-if="header.sortable===false" :key="header.text">{{ header.text}}</th>
                      <th
                        v-else
                        :key="header.text"
                        :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '']"
                        @click="changeSort(header.value)"
                      >
                        <v-icon small>arrow_upward</v-icon>
                        {{ header.text }}
                      </th>
                    </template>
                  </tr>
                </template>
                <template slot="items" slot-scope="props">
                  <tr :active="props.selected" @click="props.selected = !props.selected">
                    <td>
                      <v-checkbox :input-value="props.selected" primary hide-details></v-checkbox>
                    </td>
                    <td class="text-xs-center">{{ props.item.id }}</td>
                    <td class="text-xs-center">{{ props.item.name }}</td>
                    <td class="text-xs-center">{{ props.item.slug }}</td>
                    <td class="text-xs-center">{{ props.item.icon }}</td>
                    <td class="text-xs-center">
                      <v-chip :color="props.item.color" dark>{{ props.item.color }}</v-chip>
                    </td>
                    <td class="text-xs-center">
                      <v-tooltip bottom>
                        <v-btn
                          flat
                          icon
                          color="green"
                          slot="activator"
                          @click="editItem(props.item)"
                        >
                          <v-icon small>edit</v-icon>
                        </v-btn>
                        <span>编辑</span>
                      </v-tooltip>
                      <v-tooltip bottom>
                        <v-btn
                          flat
                          icon
                          color="red"
                          slot="activator"
                          @click="deleteItem(props.item)"
                        >
                          <v-icon small>delete</v-icon>
                        </v-btn>
                        <span>删除</span>
                      </v-tooltip>
                    </td>
                  </tr>
                </template>
              </v-data-table>
              <div class="text-xs-left pt-2">
                <v-btn color="primary" dark @click="toggleReverse(tags)">反选</v-btn>
                <v-btn color="red" dark @click="deleteSelected">删除选中</v-btn>
              </div>
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import _ from 'lodash'
import { getAllTags, createTag, updateTag, deleteTag } from '@/api/resource/tags'
import Toast from '@/plugins/toast'
export default {
  name: 'tag-list',
  data: () => ({
    headers: [
      { text: 'ID', value: 'id' },
      { text: '标题', value: 'name' },
      { text: '标识', value: 'slug' },
      { text: '图标', value: 'icon' },
      { text: '颜色', value: 'color' },
      { text: '操作', value: 'action', sortable: false }
    ],
    dialog: false,
    loading: true,
    search: '',
    totalTags: 0,
    tags: [],
    selected: [],
    pagination: {},
    editedIndex: -1,
    editedItem: {
      id: 0,
      name: '',
      slug: '',
      icon: '',
      color: ''
    },
    defaultItem: {
      id: 0,
      name: '',
      slug: '',
      icon: '',
      color: ''
    },
    color: ['red', 'pink', 'purple', 'indigo', 'blue', 'light-blue', 'cyan', 'teal', 'green', 'orange', 'brown', 'grey']
  }),
  computed: {
    formTitle () {
      return this.editedIndex === -1 ? '新建标签' : '编辑标签'
    }
  },
  watch: {
    dialog (val) {
      val || this.close()
    },
    pagination: {
      handler () {
        this.init()
      },
      deep: true
    }
  },
  methods: {
    toggleAll () {
      let _this = this
      if (_this.selected.length) _this.selected = []
      else _this.selected = _this.tags.slice()
    },
    toggleReverse (items) {
      this.selected = _.difference(items, this.selected)
    },
    changeSort (column) {
      let _this = this
      if (_this.pagination.sortBy === column) {
        _this.pagination.descending = !_this.pagination.descending
      } else {
        _this.pagination.sortBy = column
        _this.pagination.descending = false
      }
    },
    init () {
      let _this = this
      let params = {
        perPage: _this.pagination.rowsPerPage,
        page: _this.pagination.page,
        sortBy: ((_this.pagination.sortBy) ? _this.pagination.sortBy : `id`) + `,` + ((_this.pagination.descending === true) ? `desc` : `asc`)
      }
      if (_this.search) {
        params.search = _this.search
      }
      _this.loading = true
      getAllTags({ 'params': params }).then(res => {
        _this.tags = res.data
        _this.totalTags = res.meta.pagination.total
        _this.loading = false
      })
    },
    editItem (item) {
      let _this = this
      _this.editedIndex = _this.tags.indexOf(item)
      _this.editedItem = Object.assign({}, item)
      _this.dialog = true
    },
    deleteItem (item) {
      let _this = this
      const index = _this.tags.indexOf(item)
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteTag(item.id).then(res => {
            _this.tags.splice(index, 1)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    deleteSelected (items) {
      let _this = this
      let ids = []
      if (_this.selected.length === 0) {
        Toast.error({ msg: '请选择' })
        return false
      }
      _(_this.selected).forEach(function (value) {
        ids.push(value.id)
      })
      ids = ids.join()
      _this.$swal.fire({
        title: '你确定删除吗？',
        text: '删除后无法恢复!',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(result => {
        if (result.value) {
          deleteTag(ids).then(res => {
            _this.tags = _.difference(_this.tags, _this.selected)
            _this.$swal.fire(
              '已删除!',
              '选中项已被删除.',
              'success'
            )
          })
        }
      })
    },
    save () {
      let _this = this
      let index = _this.editedIndex
      let item = _this.editedItem
      _this.$validator.validateAll().then(result => {
        if (result) {
          if (index > -1) {
            updateTag(item.id, item).then(res => {
              Object.assign(_this.tags[index], item)
              Toast.success({ msg: '修改成功' })
            })
          } else {
            createTag(item).then(res => {
              _this.tags.push(res.data)
              Toast.success({ msg: '添加成功' })
            })
          }
          _this.close()
        }
      })
    },
    close () {
      let _this = this
      _this.dialog = false
      _this.editedItem = Object.assign({}, _this.defaultItem)
      _this.editedIndex = -1
    }
  },
  created () {
    this.init()
  }
}
</script>
